const DefaultServerUrl = "http://10.1.23.222:8080/";
export var Server = {
    login : async (userName, userPassword, ServerUrl) => {
        if(!ServerUrl) ServerUrl = DefaultServerUrl;
        const userData = {
          "userName"    :userName,
          "password"    :userPassword,
        }
        const ret = await post(ServerUrl + "db/login/", userData);
        return ret;
    },

    register : async(userName, userPassword,question,answer, ServerUrl) => {
      if(!ServerUrl) ServerUrl = DefaultServerUrl;
      const userData = {
        "userName"    :userName,
        "password"    :userPassword,
        "question"    : question,
        "answer"      : answer,
      }
      const ret = await post(ServerUrl + "db/register/", userData);
      return ret;
    },

    resetPassword :async(userName, userPassword,question,answer, ServerUrl) => {
      if(!ServerUrl) ServerUrl = DefaultServerUrl;
      const userData = {
        "userName"    :userName,
        "password"    :userPassword,
        "question"    : question,
        "answer"      : answer,
      }
      const ret = await post(ServerUrl + "db/resetPassword/", userData);
      return ret;
    },
}



async function post(url, data){
    const controller = new AbortController();
    setTimeout(() => controller.abort(), 5000);
    console.log(`服务器POST请求：${url}:`,data);
    try{
      const response = await fetch(url,
        {
          method:'POST',
          mode:"cors",
          headers: {'Content-Type': 'application/json'},
          body:JSON.stringify(data),
          signal :controller.signal
        });
      if(response.status !== 200){
        console.error(await response.json());
        throw {code: 1, mes:"请求服务器失败。"};
      }
      const responseData = await response.json();
      console.log(responseData);
      return {code: responseData.code, mes:responseData.mes};
    }catch(error){
      return {code: 408, mes:error.toString().split(':')[1]};
    }
  }